/**
 * 远光ECP平台3.0版本 http://www.ygsoft.com/ Grace [Gris Application Cloud-Computing
 * Extension]
 * Copyright(c) 1998 - 2020 YGSoft.Inc, All Rights Reserved
 * 
 * ecp.component.upload.js
 * 
 * 对ecp.component.webUpload上传控件进行封装，处理控件渲染，包括单个项目和多个项目的渲染
 * 
 * 变更版本：
 * Created by zhengxianwei@ygsoft.com 2016-07-13
 */
define(["jquery", "ecp.service", "ecp.utils", "ecp.utils.i18n"],function($, $ecpService, utils, i18n){
	/**
	 * 默认参数.
	 */
	var defaultOption = {
		upload : {
			beanId: "com.ygsoft.ecp.web.service.context.IFileAccessContext",
			method: "saveFile",
			jcls: "com.ygsoft.ecp.service.unstructure.EntityAttachmentSummaryVO",
			attachmentBeanId: "com.ygsoft.ecp.service.unstructure.service.context.IEntityAttachmentContext",
			attachmentQuery: "getSummariesByYwkey",
			attachmentQueryByResId: "getSummaryByResId",
			attachmentUpdate: "updateSummariesBySummaries",
			attachmentBatchDel: "deleteDetailsBySummaries",
			attachmentDel: "deleteSummaryAndDetailByResId",
			attachmentUpdateYwKey: "updateSummaryYwkeyByOldkey"
		}
	};
	var rs = $ecpService.RemoteService,
		attachmentVoList = [],
		FPP_STR = '<span style="display:none;"><input name="attachmentValue"/><div id="filePickerPlace{{time}}"></div></span>';
	/**
	 * 声明EcpUploader对象.
	 */
	var EcpUploader = function(control,option){
		if(!control || control.length === 0){return;}
		this.init(control,option);
		this.render();
	}
	
	/**
	 * 通过原型定义相关方法，比如渲染、赋值等等.
	 */
	EcpUploader.prototype = {
		/**
		 * 初始化.
		 * @param {Object} control 占位符
		 * @param {Object} option 控件渲染配置属性
		 */
		init: function(control,option){
			this.control = control;
			this.option = $.extend(true, {}, defaultOption, option);
			var contianer = option.contianer;
			if(!contianer || contianer.length === 0){
				contianer = $("body");
			}
			this.contianer = contianer;
		},
		
		/**
		 * 渲染.
		 */
		render: function(){
			var opt = this.option;
			//获得业务Id
			this.ywKey = this.getYwKey(); 
			//面板
			if(opt.showPanel){
				//修改
				if(opt.ywKey){
					this.queryFileByYwKey(opt.ywKey);
				}else{
					//新增
					this.showPanelRender([]);
				}
			}else{
				//单个项目
				this.simpleRender();
			}
		},
		
		/**
		 * 面板展现渲染控件.
		 * @param {Array} data 数据对象
		 */
		showPanelRender: function(data){
			//将面板加入到容器中
			var me = this;
			require(["ecp.component.uploadPanel"],function(){
				var res = me.changeFileData(data);
				var opt = {
					disabled: me.option.disabled,
					data: res,
					files: data,
					uploadClick: function(){
						me.popAttachManege();
					}
				}
				me.control.uploadPanel(opt);
			});
		},
		
		/**
		 * 处理文件数据.
		 * @param {Array} data 文件数据
		 */
		changeFileData: function(data){
			if(!data || data.length === 0){return [];}
			var res = [],
				dc = $ecpService.DataContextUtil,
				orgId = dc.getLoginOrgId(),
				userId = dc.getUserId();
	 		$.each(data,function(){
	 			var file = this;
	 			file.fileName = file.title;
	 			file.fileSize = file.bsize;
	 			file.fileType = file.btype;
	 			file.url = utils.getAttachmentDownLoadURL(file,userId,orgId);
	 			res.push(file);
	 		})
	 		return res;
		},
		
		/**
		 * 弹出附件管理界面.
		 */
		popAttachManege: function(){
			var me = this;
			require(["ecp.component.uploadManage"],function(uploadManage){
				var opt = {
				        //业务主键
				        ywKey: me.getYwKey(),
				        //关闭回调给附件面板赋值
						closeCallBack: function(data){
					 		if(!utils.notEmpty(data)){return;}
					 		me.control.uploadPanel("destroy");
					 		var res = me.changeFileData(data);
					 		me.control.uploadPanel("val", res);
				 		}
				 }
				 $("body").uploadManage(opt);
			 });
		},
		
		/**
		 * 单个项目渲染.
		 */
		simpleRender: function(){
			var me = this,
				ct = me.control,
				opt = me.option,
				time = new Date().getTime(),
				fppStr = FPP_STR.replace("{{time}}",time);
			ct.before(fppStr);
			//初始化项目值
			if(utils.notEmpty(opt.resId)){
				me.queryFileByResId(opt.resId);
			}
			require(["ecp.component.webUpload"],function(webUpload){
				//渲染上传组件
			    var uploadOpt = {};
			    //保存文件回调函数
			    uploadOpt.filesQueued = function(files, filesOpt){
			    	me.saveFile(files, filesOpt, this.uploader);
			    };
			    if(opt.webuploader){
			    	uploadOpt = $.extend(uploadOpt,opt.webuploader);
			    }
			    var uploadControl = $("#filePickerPlace"+time,me.contianer);
			    //渲染上传控件
			    me.uploader = uploadControl.webUpload(uploadOpt);
			    //绑定上传控件
			    ct.next().off("click").on("click", function(){
			    	if(me.disable === true){
			    		return;
			    	}
			    	uploadControl.find("label").click();
			    })
			})
		},
		
		/**
		 * 获得上传组件对象.
		 */
		getUploader: function(){
			 return this.uploader;
		},
		
		/**
		 * 设置或获取附件值.
		 */
		value: function(value){
			 var me = this,
			 	 ct = me.control,
			 	 opt = me.option;
			 if(arguments.length > 0){
				 me.initValue(value);
			 }else{
				 var res;
				 //单个项目
				 if(!opt.showPanel){
					 res = ct.val();
				 }
				 return res;
			 }
		},
		
		/**
		 * 设置显示值.
		 */
		initValue: function(value){
			 if(arguments.length === 0){return;}
			 var me = this,
			 	 ct = me.control,
			 	 opt = me.option;
			 ct.val(value);
		},
		
		/**
		 * 保存文件
		 */
		saveFile: function(files){
			if(!files){return;}
			var me = this,
				params = [], 
				param, time,
				resIds = [],
				fileNames = [],
				opt = me.option,
				resId = opt.resId, 
				uploadOpt = opt.upload,
				beanId = uploadOpt.beanId,
				method = uploadOpt.method,
				jcls = uploadOpt.jcls,
				uploader = me.uploader.uploader;
			if(!uploader){return;}
			//校验单个附件大小是否超过20M  20 * 1024 * 1024=20971520
			for(var i = 0,j=files.length; i<j; i++){
				if(files[i].size > 20971520){
					utils.notify(i18n.upload.sizeError);
					return;
				}
				//类型校验
				if($.inArray(files[i].ext.toLocaleLowerCase(), ["exe","dll"]) > -1){
					utils.notify(i18n.upload.sizeError + files[i].ext + i18n.upload.typeError);
					return;
				}
			}
			try{
				var title,modelState,
					dc = $ecpService.DataContextUtil,
					userId = dc.getUserId(),
					orgId = dc.getLoginOrgId();
				$.each(files,function(i,file){
					if(!resId){
						resId = Math.uuid();
						modelState = 4;
					}else{
						modelState = 8;
					}
					resIds.push(resId);
					time = new Date().getTime();
					title = file.name.toUpperCase();
					fileNames.push(title);
					title = title.substring(0,title.lastIndexOf("."));
		    		param = {
		        		   ywkey:me.getYwKey(),
		        		   resId: resId,
		        		   remark:"",
		        		   title: title,
		        		   bsize:file.size,
		        		   bsort:2,
		        		   btype:file.ext.toUpperCase(),
		        		   modelState:4,
		        		   status:0, 
		        		   userid:+userId,
		        		   attachmentDetailVO:{}
		    		};
		    		uploader.options.server = '/grm/ecp/webcore/FileAccessServlet?beanId='+beanId+'&method='+method+'&'+
		           	'operParams=[null,'+ $.toJSON(param) +',"'+orgId+'"]&_token=' + $.cookie("ecpDataContext.tokenId") +'&tParam=' + time;
		    		//提交到服务端保存
		    		uploader.upload();
		    		
					var acVo = param;
					acVo.jcls = jcls;
					acVo.modelState = modelState;
					delete acVo.attachmentDetailVO;
					attachmentVoList.push(acVo);
				})
	    		if(!opt.showPanel){
	    			//把文件名和主键值写到控件上
		    		me.control.parent().find("[name='attachmentValue']").val(resIds.join(";"));
		    		me.control.val(fileNames.join(";"));
	    		}
				utils.notify(i18n.upload.success);
			}catch(e){
				utils.notify(i18n.upload.success);
			}
			
		},
		
		/**
		 * 通过ywKey查询文件.
		 */
		queryFileByYwKey: function(ywkey){
			var me=this,
				uploadOpt = me.option.upload,
				beanId = uploadOpt.attachmentBeanId,
				method = uploadOpt.attachmentQuery;
			if(!beanId || !method){
				return;
			}
			rs.doPostAsync(beanId, method, [ywkey], function(res){
				if (res.isError()) {
					if(window.console){
						window.console.error(i18n.upload.hxError + res.data);
					}
					return;
				} else {
					me.showPanelRender(res.data);
				}
			});
		},
		
		/**
		 * 通过resId查询文件.
		 */
		queryFileByResId: function(resId){
			var me=this,
				ct = me.control,
				uploadOpt = me.option.upload,
				beanId = uploadOpt.attachmentBeanId,
				method = uploadOpt.attachmentQueryByResId;
			if(!beanId || !method){
				return;
			}
			rs.doPostAsync(beanId, method, [resId], function(res){
				if (res.isError()) {
					if(window.console){
						window.console.error(i18n.upload.hxError + res.data);
					}
					return;
				} else {
					if(res.data){
						//设置显示值
						ct.val(res.data.title);
						//设置ID值
						ct.parent().find("[name='attachmentValue']").val(res.data.resId);
					}
//					me.showPanelRender(res.data);
				}
			});
		},
		
		/**
		 * 回写业务KEY.
		 * 保存时用新的业务key替换临时业务key
		 * @param {String} newYwKey 新的业务key
		 * @param {String} oldYwKey 旧的业务key
		 */
		updateTempYwKey: function(newYwKey){
			var me=this,
				uploadOpt = me.option.upload,
				beanId = uploadOpt.attachmentBeanId,
				method = uploadOpt.attachmentUpdateYwKey;
			if(!beanId || !method){
				return;
			}
			var oldYwKey = me.getYwKey();
			if(oldYwKey === newYwKey){return;}
			rs.doPostAsync(beanId, method, [newYwKey, oldYwKey], function(res){
				if (res.isError()) {
					if(window.console){
						window.console.error(i18n.upload.hxError + res.data);
					}
				} else {
					if(window.console){
						window.console.info(i18n.upload.hxSuccess);
					}
				}
			});
		},
			
		/**
		 * 删除文件
		 */
		deleteFile: function(){
			var resId = $me.parent().attr("resId");
	        if(!resId){return;}
	        var uploadOpt = this.option.upload;
			var beanId = uploadOpt.attachmentBeanId;
			var method = uploadOpt.attachmentDel;
			if(!beanId || !method){
				return;
			}
			rs.doPostAsync(beanId, method, [resId], function(res){
				if (res.isError()) {
					utils.notify(i18n.upload.delError + res.data);
				}else{
					utils.notify(i18n.upload.delSuccess);
				}
			})
		},
		/**
		 * 批量删除已保存的文件（文件上传成功了，但是单据没有保存，这时候要删除之前上传的文件）
		 */
		batchDeleteFile: function(){
			var uploadOpt = this.option.upload;
			var beanId = uploadOpt.attachmentBeanId;
			var method = uploadOpt.attachmentBatchDel;
			if(!beanId || !method){
				return;
			}
			rs.doPostAsync(beanId,method,[attachmentVoList], function(res){
				if (res.isError()) {
					utils.notify(i18n.upload.batchDelError + res.data);
				}else{
					utils.notify(i18n.upload.batchDelSuccess);
				}
			})
		},
		/**
		 * 修改文件
		 */
		modifyFile: function(){
			var uploadOpt = this.option.upload;
			var beanId = uploadOpt.attachmentBeanId;
			var method = uploadOpt.attachmentUpdate;
			if(!beanId || !method){
				return;
			}
			//修改附件 
			rs.doPostAsync(beanId, method, [attachmentVoList], function(res){
				if (res.isError()) {
					//return;
				}else{
//					notifyMsg("保存附件成功。");
				}
			});
		},
		/**
		 * 设置ywKey.
		 */
		setYwKey: function(key){
			this.ywKey = key;
		},
		/**
		 * 获取ywKey.
		 */
		getYwKey: function(){
			var opt = this.option,
				ywKey = opt.ywKey;
			if(this.ywKey){
				ywKey = this.ywKey;
			}else if(!utils.notEmpty(ywKey)){
				this.ywKey = ywKey = Math.uuid();
			}
			return ywKey;
		}
	};
	(function($) {
		var old = $.fn.ecpUploader;
		$.fn.ecpUploader = function(option){
			var me = this;
			option = option || {};
			var type = typeof(option);
			//如果第一个参数传入的是对象或空则初始化空件，如果传入的是字符串，则认为是调用里面的内部方法。
			if (type === "object") {
				var eus = [];
				this.each(function() {
					var instanceOption = $.extend({}, option, true);
					var instance = new EcpUploader($(this), instanceOption);
					this.ecpUploader = instance;
					eus.push(instance);
				});
				if(eus.length === 1){
					eus = eus[0];
				}
				return eus;
			} else if (type === "string") {
				var args = Array.prototype.slice.call(arguments, 1);
				if (EcpUploader.prototype[option]) {
					return EcpUploader.prototype[option].call(args);
				}
			} else if (option === true) {
				return me[0] && me[0].ecpUploader;
			}
		};
		$.fn.ecpUploader.Constructor = EcpUploader;
		$.fn.ecpUploader.noConflict = function() {
			$.fn.ecpUploader = old;
			return this;
		};
	}(jQuery));
	return EcpUploader.prototype;
		
});